from reedsolo import RSCodec
import random
import base64
def RsEnCode(msg,len=16):
    ecc=RSCodec(len)#纠错码字长度，可纠正len/2个误读
    return ecc.encode(bytearray(msg,'utf-8'))
def RsDecode(encode,len=16):
    ecc=RSCodec(len)
    data=ecc.decode(encode)
    return data[0].decode()

msg=RsEnCode("纠错码字长度，可纠正n/2个误读")
b64=base64.b64encode(msg)
print(b64)
print(RsDecode(msg))
print(RsDecode(base64.b64decode(b64)))
ecc=RSCodec(128)#纠错码字长度，可纠正n/2个误读
aa=bytearray('小明123','utf-8')
print(aa)

binary_code=''.join(format(x,'08b') for x in aa) #转二进制
print(len(binary_code),binary_code)

bytes_msg=bytes(int(binary_code[i:i+8],2)for i in range(0,len(binary_code),8))
array_msg=bytearray(bytes_msg)
print(array_msg)



#编码
byte_msg=ecc.encode(aa) #8个字符+6个纠错字=14字符=14*8位
print(byte_msg)
#转换为二进制
binary_code=''.join(format(x,'08b') for x in byte_msg)
print(len(binary_code),type(binary_code))
print(binary_code)
data=ecc.decode(byte_msg)
#污染二进制
binary_code=list(binary_code)

for i in range(0,3):
    er=random.randint(0,len(binary_code))
    binary_code[er]="0" if binary_code[er]=="1" else "1"
    print(er*" "+"1")
# binary_code[5*8+5]=str(1-int(binary_code[3*8+5]))#再错就无法纠正信息
binary_code=''.join(binary_code)
print(binary_code)

bytes_msg=bytes(int(binary_code[i:i+8],2) for i in range(0,len(binary_code),8))
array_msg=bytearray(bytes_msg)
#再纠错
data=ecc.decode(array_msg)
msg=data[0].decode()
print(data[0])
print(aa)
print(msg)
